package com.lxinet.jeesns.core.interceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lxinet.jeesns.core.annotation.After;
import com.lxinet.jeesns.core.annotation.Before;
import com.lxinet.jeesns.core.annotation.Clear;
import com.lxinet.jeesns.core.utils.ConfigUtil;
import com.lxinet.jeesns.core.utils.Const;
import com.lxinet.jeesns.core.utils.JeesnsConfig;
import com.lxinet.jeesns.core.utils.MemberUtil;
import com.lxinet.jeesns.core.utils.SpringContextHolder;
import com.lxinet.jeesns.core.utils.StringUtils;
import com.lxinet.jeesns.modules.mem.entity.Member;
import com.lxinet.jeesns.modules.mem.service.IMessageService;
import com.lxinet.jeesns.modules.sys.service.IConfigService;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by zchuanzhao on 16/9/26.
 */
public class InitInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        if(StringUtils.isEmpty(Const.PROJECT_PATH)){
            Const.PROJECT_PATH = httpServletRequest.getContextPath();
        }
        httpServletRequest.setAttribute("base",Const.PROJECT_PATH);
        JeesnsConfig jeesnsConfig = SpringContextHolder.getBean("jeesnsConfig");
        httpServletRequest.setAttribute("jeesnsConfig",jeesnsConfig);
        String managePath = Const.PROJECT_PATH + "/" + jeesnsConfig.getManagePath();
        httpServletRequest.setAttribute("managePath",managePath);
        IConfigService configService = SpringContextHolder.getBean("configService");
        IMessageService messageService = SpringContextHolder.getBean("messageService");
        Member loginUser = MemberUtil.getLoginMember(httpServletRequest);
        httpServletRequest.setAttribute("loginUser",loginUser);
        //会员未读私信数量
        Integer unReadMessageNum = 0;
        if (loginUser != null) {
            if(loginUser.getIsActive() == 0){
                Map<String,String> configMap = configService.getConfigToMap();
                if(Integer.parseInt(configMap.get(ConfigUtil.MEMBER_EMAIL_VALID)) == 1){
                    if(!(httpServletRequest.getServletPath().contains("member/active")
                        || httpServletRequest.getServletPath().contains("member/logout") ||
                        httpServletRequest.getServletPath().contains("member/sendEmailActiveValidCode")
                        || httpServletRequest.getServletPath().contains("/res/") ||
                        httpServletRequest.getServletPath().contains("/upload/"))){
                        httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/member/active");
                        return false;
                    }
                }
            }
            unReadMessageNum = messageService.countUnreadNum(loginUser.getId());
        }
        httpServletRequest.setAttribute("unReadMessageNum",unReadMessageNum);

        configService.allList().forEach(config -> httpServletRequest.setAttribute(config.getJkey().toUpperCase(), config.getJvalue()));

        if(handler != null){
            if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
                Class clazz = ((HandlerMethod)handler).getMethod().getDeclaringClass();

                if (clazz.isAnnotationPresent(Before.class) && !((HandlerMethod)handler).getMethod().isAnnotationPresent(Clear.class)) {
                    for (Annotation annotation : clazz.getAnnotations()) {
                        if (annotation instanceof Before) {
                            Before before = (Before)annotation;
                            Class<? extends JeesnsInterceptor> interceptorlll = before.value();
                            Object object = Class.forName(interceptorlll.getCanonicalName()).newInstance();
                            Class[] clazzs = new Class[] {HttpServletRequest.class, HttpServletResponse.class,
                                Object.class};
                            Method method = object.getClass().getMethod("interceptor", clazzs);
                            Object[] params = new Object[] {httpServletRequest, httpServletResponse, handler};
                            return (boolean)method.invoke(object, params);
                        }
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) throws Exception {
        if(handler != null){
            if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
                Class clazz = ((HandlerMethod)handler).getMethod().getDeclaringClass();
                if (clazz.isAnnotationPresent(After.class) && !((HandlerMethod)handler).getMethod().isAnnotationPresent(Clear.class)) {
                    for (Annotation annotation : clazz.getAnnotations()) {
                        if (annotation instanceof After) {
                            After after = (After) annotation;
                            Class<? extends JeesnsInterceptor> interceptorlll = after.value();
                            Object object = Class.forName(interceptorlll.getCanonicalName()).newInstance();
                            Class[] clazzs = new Class[]{HttpServletRequest.class,HttpServletResponse.class,Object.class};
                            Method method = object.getClass().getMethod("interceptor",clazzs);
                            Object[] params = new Object[]{httpServletRequest,httpServletResponse,handler};
                            method.invoke(object,params);
                        }
                    }
                }
            }
        }
    }
}
